package org.extframework.ld.http.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import org.extframework.ld.bean.Entity;
import org.extframework.ld.conf.ParameterNames;
import org.extframework.ld.content.ExtContent;
import org.extframework.ld.control.ExtJsonControl;
import org.extframework.ld.http.abstr.AbstractEncryptionWebRequest;
import org.extframework.ld.http.abstr.AbstractEncryptionWebResponse;
import org.extframework.ld.http.abstr.AbstractEncryptionWebServlet;
import org.extframework.ld.service.SysManager;
import org.extframework.ld.service.pojo.DefaultSysManager;
import org.extframework.ld.util.ExtMessage;
import org.extframework.ld.xml.base.ComboBoxData;
import org.extframework.ld.xml.base.ComboBoxDataDetail;
import org.extframework.ld.xml.base.ExtParameter;

import com.alibaba.fastjson.JSON;

/**
 * @author : Dong.Li
 * @created : 2013-1-21
 * @version : 1.0
 * @description :
 */
public class SysServlet extends AbstractEncryptionWebServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void index(AbstractEncryptionWebRequest paramHttpServletRequest,
			AbstractEncryptionWebResponse paramHttpServletResponse)
			throws ServletException, IOException {
		
	}

	protected void init(
			AbstractEncryptionWebRequest paramAbstractEncryptionWebRequest,
			AbstractEncryptionWebResponse paramAbstractEncryptionWebResponse)
			throws ServletException, IOException {

		this.sysManager = ((SysManager) getBean(DefaultSysManager.class));
	}

	private SysManager sysManager;

	public void fun(AbstractEncryptionWebRequest request,
			AbstractEncryptionWebResponse response) throws IOException {
		String paramStr = request.getParameter("param");
		String actionStr = request.getParameter("action");

		String[] actions = actionStr.split("\\.");
		String className = actions[0];
		String method = actions[1];

		Object obj = request.getSession().getAttribute(
				ParameterNames.LOGIN_USER_MARK);

		if (paramStr == null) {
			response.printJson(ExtMessage.showErrorMessage("页面异常,请刷新页面后再试"));
			return;
		}

		if (obj == null) {
			response.printJson(ExtMessage.showErrorMessage("登录超时,请刷新页面后再试"));
			return;
		}

		paramStr = paramStr.replaceAll(ParameterNames.PARMETER_MARK,
				((Entity) obj).getId().toString());

		Object object = getBean(className);
		try {
			List<ExtParameter> parameters = JSON.parseArray(paramStr,
					ExtParameter.class);

			parameters.get(0).getMap().put("request", request);
			parameters.get(0).getMap().put("response", response);
			parameters.get(0).getMap().put("sessionUser", obj);

			Method methodClass = object.getClass().getDeclaredMethod(method,
					new Class[] { List.class });
			Object msg = methodClass
					.invoke(object, new Object[] { parameters });
			if (msg == null) {
				response.printJson(ExtMessage.showMessage("操作成功"));
				return;
			}
			response.printJson(msg.toString());
		} catch (SecurityException e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
			response.printJson(ExtMessage.showErrorMessage(e.getMessage()));
		} catch (NoSuchMethodException e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
			response.printJson(ExtMessage.showErrorMessage(e.getMessage()));
		} catch (IllegalArgumentException e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
			response.printJson(ExtMessage.showErrorMessage(e.getMessage()));
		} catch (IllegalAccessException e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
			response.printJson(ExtMessage.showErrorMessage(e.getMessage()));
		} catch (InvocationTargetException e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
			response.printJson(ExtMessage.showErrorMessage(e.getMessage()));
		}

	}

	public void remoteComboBox(AbstractEncryptionWebRequest request,
			AbstractEncryptionWebResponse response) throws IOException {
		String cdIdStr = request.getParameter("cdId");

		String limitStr = request.getParameter("limit");
		String queryStr = request.getParameter("query");
		String startStr = request.getParameter("start");

		String hql = ExtContent.getcomBoxHql(cdIdStr);

		Object obj = request.getSession().getAttribute(
				ParameterNames.LOGIN_USER_MARK);
		if (obj == null) {
			response.printError("登录超时！");
		}
		hql = hql.replaceAll("#user#", ((Entity) obj).getId().toString());

		if ((queryStr != null) && (queryStr.length() > 1)) {
			hql = hql.replaceAll(":parem", "'%" + queryStr + "%'");
			hql = hql.replaceAll("#", "");
		} else {
			hql = hql.replaceAll("#.*#", "");
		}

		int start = 0;
		int end = 6;
		try {
			start = Integer.parseInt(startStr);
			end = Integer.parseInt(limitStr);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		Map<String, List<Object[]>> map = this.sysManager.getObjects(hql,
				start, end, new Object[0]);

		ComboBoxData boxData = new ComboBoxData();
		for (Object[] objs : map.entrySet().iterator().next().getValue()) {
			ComboBoxDataDetail boxDataDetail = new ComboBoxDataDetail();
			boxDataDetail.setId(objs[0].toString());
			boxDataDetail.setValue(objs[1].toString());
			boxData.getDetails().add(boxDataDetail);
		}
		boxData.setTotalNum(Integer.parseInt(map.entrySet().iterator().next()
				.getKey()));
		response.printJson(ExtJsonControl.toJson(boxData));
	}


}
